/*
 * Copyright (c) 2018, dreamkaylee@foxmail.com All Rights Reserved.
 */

package com.common.shiro.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import com.google.code.kaptcha.Constants;

/**
 * 扩展FormAuthenticationFilter实现kaptcha验证码校验
 * 
 * @author limk
 * @date 2018年2月12日 下午9:03:14
 * @version 1.0
 */
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {

	public static final String DEFAULT_CAPTCHA_PARAM = "captcha";
	
	private String captcha = DEFAULT_CAPTCHA_PARAM;
	
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		
		HttpServletRequest req = (HttpServletRequest) request;
		
		String captcha = request.getParameter(DEFAULT_CAPTCHA_PARAM);
		
		String vvcode = (String) req.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
		
		if (vvcode == null || "".equals(vvcode) || !vvcode.equals(captcha)) {
			req.setAttribute("shiroLoginFailure", "randomCodeError");
			return true;
		}
		return super.onAccessDenied(request, response);
	}

	public String getCaptcha() {
		return captcha;
	}

	public void setCaptcha(String captcha) {
		this.captcha = captcha;
	}
	
}
